package idc

import (
	"sync"
	"wzgames/pkg/components/mysql"
)

type IdWorker struct {
	sync.RWMutex

	idBizImpl map[int64]*IdBiz // 按业务ID区分

	dao IdDao
}

func NewIdWorker() *IdWorker {
	return &IdWorker{
		idBizImpl: make(map[int64]*IdBiz),
	}
}

func (w *IdWorker) SetDao(ds *mysql.DS) {
	w.Lock()
	defer w.Unlock()
	w.dao = IdDao{Driver: ds.Ds()}
}

// ID 根据业务ID 获取一个或者一段ID
func (w *IdWorker) ID(bizid int64, step uint64) uint64 {
	w.RLock()
	if b, ok := w.idBizImpl[bizid]; ok {
		w.RUnlock()
		return b.getID(bizid, step)
	}
	w.RUnlock()

	w.Lock()
	defer w.Unlock()
	if b, ok := w.idBizImpl[bizid]; ok {
		return b.getID(bizid, step)
	}

	idb := newIdBiz(bizid, w)
	w.idBizImpl[bizid] = idb

	return idb.getID(bizid, step)
}
